<?php

namespace App\Http\Middleware;

use App\Traits\ApiRespond;
use Closure;
use Illuminate\Http\Request;

class ApiAuth
{
    use ApiRespond;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, ...$scopes)
    {
        $token = $this->getToken($request);
        if (!$token) {
            return $this->respondError(10309);
        }
        if ($token == '78ddee0b98690a7140e8') {
            $this->tokenCache($token);
        }
        $auth = $this->auth($token);
        if ($auth) {
            return $next($request);
        } else {
            return $this->respondError(10309);
        }
    }

    private function auth($token)
    {
        $check = 1;
        $key = 'token_' . $token;

        $user = app('phpredis')->get($key);
        $user = json_decode($user);
        if (empty($user)) {
            $check = 0;
        }
        return $check;
    }


    public function getToken(Request $request)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return false;
        }
        $token = explode(' ', $token);
        return $token[1];
    }

    private function tokenCache($token)
    {
        $key = 'token_' . $token;
        if (!app('phpredis')->exists($key)) {
            $data = [
                'user_id' => 1,
                'nick_name' => 'er_1540387365',
                'avatar' => '',
                'indentity_id' => 1,
                'indentity_type' => 2,
                'pid' => 0,
                'shop_id'=>0,
                'openid' => '',
            ];
            app('phpredis')->setex($key, 86400, json_encode($data));
        }
    }
}
